package com.cyl.manager.ums.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.manager.oms.domain.entity.Order;
import com.cyl.manager.oms.mapper.AftersaleMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.domain.entity.MemberCart;
import com.cyl.manager.ums.domain.form.ChangeMemberStatusForm;
import com.cyl.manager.ums.domain.query.MemberQuery;
import com.cyl.manager.ums.domain.query.MemberTopQuery;
import com.cyl.manager.ums.domain.vo.MemberDataStatisticsVO;
import com.cyl.manager.ums.domain.vo.MemberTopVO;
import com.cyl.manager.ums.mapper.MemberCartMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.github.pagehelper.PageHelper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.AesCryptoUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SortUtil;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.system.service.ISysDeptService;

import io.swagger.annotations.ApiModelProperty;

/**
 * 会员信息Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Value("${aes.key}")
    private String aesKey;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private MemberCartMapper memberCartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AftersaleMapper aftersaleMapper;

    @Autowired
    private ISysDeptService deptService;
    
    
    /**
     * 查询会员信息
     *
     * @param id 会员信息主键
     * @return 会员信息
     */
    public Member selectById(Long id) {
        return memberMapper.selectById(id);
    }
    

    public Member selectMemberByOid(String openid) {
		QueryWrapper<Member> qw = new QueryWrapper<>();
		 qw.eq("openid", openid);
	    List<Member> list =  memberMapper.selectList(qw);
	    if(list!=null && list.size()>=0) {
	    	return list.get(0);
	    }
		return null;

    }
    
    /**
     * 查询店长列表
     * @param query
     * @return
     */
    public List<Member> selectListDzAll(MemberQuery query) {
		QueryWrapper<Member> qw = new QueryWrapper<>();
		Long qrDeptZbjId = query.getDeptZbjId();
	    if(qrDeptZbjId!=null) {
	         qw.eq("dept_zbj_id", qrDeptZbjId);
	    }
	    qw.eq("rolezd", 2);
	    List<Member> list =  memberMapper.selectList(qw);
		return list;

    }

    
    /**
     * 查询店铺的店长和核销人员(工作人员)
     * @param deptDpId 店铺
     * @param page 分页条件
     * @return 工作人员会员信息
     */
    public List<Member> selectListDpry(Long  deptDpId, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(), SortUtil.sort2string(page.getSort(),"rolezd desc, id desc"));
        }
        QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
        queryWrapper.eq("dept_dp_id", deptDpId);
        ArrayList<Integer> rolezds = new ArrayList<Integer>();
        rolezds.add(1);
        rolezds.add(3);
        rolezds.add(2);
        queryWrapper.in("rolezd",rolezds);
        return memberMapper.selectList(queryWrapper);
    }
    
    

    /**
     * 查询会员信息列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 会员信息
     */
    public List<Member> selectList(MemberQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(), SortUtil.sort2string(page.getSort(),"t.rolezd desc, t.id desc"));
        }
        // QueryWrapper<Member> qw = new QueryWrapper<>();
//        MPJLambdaWrapper<Member> qw = new MPJLambdaWrapper<Member>();
        MPJQueryWrapper<Member> qw = new MPJQueryWrapper<Member>();
		

        String nicknameLike = query.getNickname();
        
        String id = query.getId();
        Integer rolezd = query.getRolezd();
        Long deptTzId = query.getDeptTzId();
        Long deptDpId = query.getDeptDpId();
        // MemberAccount::getIntegralBalance, Member::getIntegral
        qw.select("t1.integral_balance as  integral, t.*");//别名
        qw.selectAll(Member.class);//查询user表全部字段
        qw.leftJoin(" ums_member_account t1 ON ( t1.member_id = t.id ) ");
        Long qxDeptId = query.getQxDeptId();
        if(qxDeptId!=null) {

            if(qxDeptId!=null) {
            	qw.join(" JOIN ", true, "  (SELECT dept_dp_id AS dept_dp_id FROM sys_dept_dept  WHERE  dept_id =  "+qxDeptId+") AS sys_dd\r\n" + 
            			"            			ON t.dept_dp_id = sys_dd.dept_dp_id  ");
            }   
        } 
    
 
        

        
        if (rolezd!=null) {
        	if(rolezd==999) {
        		List<Integer> rolezds = new ArrayList<Integer>();
        		rolezds.add(2);
        		rolezds.add(3);
        		rolezds.add(4);
                qw.in("t.rolezd", rolezds);
        	}else {
                qw.eq("t.rolezd", rolezd);
        	}
        }
        
        
     
    		
        Integer hyzt = query.getHyzt();
        if(hyzt!=null) {
            qw.eq("t.hyzt", hyzt);
        }

    	 Long qrDeptZbjId = query.getDeptZbjId();
         if(qrDeptZbjId!=null) {
             qw.eq("t.dept_zbj_id", qrDeptZbjId);
         }
         
         
        Long spreaduid = query.getSpreaduid();
        if(spreaduid!=null) {
            qw.eq("t.spreaduid", spreaduid);
        }
        if (deptTzId!=null) {
            qw.eq("t.dept_tz_id", deptTzId);
        }
        if (deptDpId!=null) {
            qw.eq("t.dept_dp_id", deptDpId);
        }
        if (!StringUtils.isEmpty(id)) {
        	try {
                qw.eq("t.id", Long.parseLong(id));
			} catch (Exception e) {
			}
        }

        List<Long> ids = query.getIds();
        if(ids!=null && ids.size()>0) {
            qw.in("t.id", ids);
        }
        
        if (!StringUtils.isEmpty(nicknameLike)) {
            qw.like("t.nickname", nicknameLike);
        }
        
        String mark = query.getMark();
        
        if (!StringUtils.isEmpty(mark)) {
            qw.like("t.mark", mark);
        }
        
        String phone = query.getPhone();
        if (!StringUtils.isEmpty(phone)) {
            qw.eq("t.phone_encrypted", AesCryptoUtils.encrypt(aesKey, phone));
        }
        if (!StringUtils.isEmpty(query.getBeginTime()) && !StringUtils.isEmpty(query.getEndTime())){
            qw.ge("t.create_time", query.getBeginTime());
            qw.lt("t.create_time", query.getEndTime());
        }
        if (query.getHasMark() != null) {
            switch (query.getHasMark()) {
                case 0:
                    qw.isNull("t.mark").or().eq("t.mark","");
                    break;
                case 1:
                    qw.isNotNull("t.mark").ne("t.mark","");
                    break;
                default:
                    break;
            }
        }
        if (query.getStatus() != null){
            qw.eq("t.status", query.getStatus());
        }
        List<Member> list =  memberMapper.selectList(qw);
        Map<Long, String> map = new HashMap<Long, String>();
        for (Member member : list) {
            Map<String, Object> params = new HashMap<String, Object>();
            Long dpid = member.getDeptDpId();
            boolean bool = false;
            if(dpid!=null) {
            	if(map.containsKey(dpid)) {
            		bool = true;
            		params.put("dpcm", map.get(dpid));
            	}else {
            		SysDept sysDept = deptService.getCacheSysDept(dpid);
            		if(sysDept!=null) {
            			bool = true;
            			map.put(dpid, sysDept.getDeptName());
                		params.put("dpcm", map.get(dpid));
            		}
            	}
            }
            if(bool == false) {
        		params.put("dpcm", "");
            }
            member.setParams(params);
		}
        return list;
    }

    /**
     * 新增会员信息
     *
     * @param member 会员信息
     * @return 结果
     */
    public int insert(Member member) {
        member.setCreateTime(LocalDateTime.now());
        return memberMapper.insert(member);
    }

    /**
     * 修改会员信息
     *
     * @param member 会员信息
     * @return 结果
     */
    public int update(Member member) {
        return memberMapper.updateById(member);
    }

    public int updateMark(Member member) {
    	
        String memberKey = Constants.MEMBER_INFO+"_"+member.getId();
        redisCache.deleteObject(memberKey);
        
        UpdateWrapper<Member> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("mark",member.getMark())
                .set("update_time",LocalDateTime.now())
                .eq("id",member.getId());
        return memberMapper.update(null,updateWrapper);
    }
    
       
    //校验订单信息
    public String checkOrder(Long memberId) {
    	String msg = null;
	    int whxdds =  orderMapper.selectOrderCountByMemberId(memberId);
		if(whxdds > 0) {
			msg =  "会员id:"+memberId+"存在["+whxdds+"]个订单未核销, 操作失败！";
		}else {
			int wzfdd = this.selectOrderCountWzf(memberId);//未支付的订单
			if(wzfdd > 0) {
				msg =  "会员id:"+memberId+"存在["+whxdds+"]个订单未支付, 操作失败！";
			}
		}
		String memberKey = Constants.MEMBER_INFO+"_"+memberId;
        redisCache.deleteObject(memberKey);
		return msg; 
    }
    
    //未支付的订单
    public int selectOrderCountWzf(Long memberId) {
    	QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
    	queryWrapper.eq("member_id", memberId);
    	queryWrapper.eq("status", 1);
    	queryWrapper.eq("aftersale_status", 1);
    	Integer wzfdd = orderMapper.selectCount(queryWrapper);
    	if(wzfdd==null) {
    		return 0;
    	}
    	return wzfdd.intValue();
    }    
    public int updateSpreaduid(Member member) {
    	Member dbMember = this.selectById(member.getSpreaduid());
    	if(dbMember==null) {
	           throw new RuntimeException("归属群主id不存在！");
    	}
    	if(dbMember.getRolezd() == 1) {
	           throw new RuntimeException("不能设置核销员id未群主id");
    	}
    	if(dbMember.getRolezd() == -1) {
	           throw new RuntimeException("未绑定店铺数据id不能设置为群主");
    	}
    	if(dbMember.getRolezd() == 0) {
	           throw new RuntimeException("不能设置普通用户未群主id");
    	}
    	
    	Member dbMember2 = this.selectById(member.getId());
    	if(!dbMember2.getDeptDpId().equals(dbMember.getDeptDpId())) {
	        throw new RuntimeException("不能跨店设置群主id");
    	}
    	
        String memberKey = Constants.MEMBER_INFO+"_"+member.getId();
        redisCache.deleteObject(memberKey);
        
        
        
        
        UpdateWrapper<Member> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("spreaduid",member.getSpreaduid())
                .set("update_time",LocalDateTime.now())
                .eq("id",member.getId());
        return memberMapper.update(null,updateWrapper);
    }

    /**
     * 删除会员信息信息
     *
     * @param id 会员信息主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return memberMapper.deleteById(id);
    }

    public Integer changeStatus(ChangeMemberStatusForm dto) {
        UpdateWrapper<Member> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", dto.getMemberId());
        wrapper.set("status", dto.getStatus());
        return memberMapper.update(null, wrapper);
    }

    public String getPhoneDecrypted(String phoneEncrypted) {
        return AesCryptoUtils.decrypt(aesKey, phoneEncrypted);
    }

    public MemberDataStatisticsVO viewStatistics(Long memberId) {
        LambdaQueryWrapper<MemberCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberCart::getMemberId, memberId);
        int cartCount = memberCartMapper.selectCount(wrapper);
        MemberDataStatisticsVO vo = orderMapper.statOrderCountAndAmount(memberId);
        vo.setCartCount(cartCount);
        vo.setAftersaleCount(aftersaleMapper.countByMemberId(memberId));
        return vo;
    }

    /**
     * 设置为店长
     * @param member
     * @return
     */
	public int updateByDz(Long deptDpId , Long memberId,int rolezd) {
		LocalDateTime localDateTime = LocalDateTime.now();

		if(memberId == null) {
	           throw new RuntimeException("会员不存在");
		}
		Member memberdb = selectById(memberId);
		if(memberdb == null) {
	           throw new RuntimeException("会员不存在");
		}
		if(deptDpId == null) {
	           throw new RuntimeException("请选择一个店铺");
		}
	
	    String memberKey = Constants.MEMBER_INFO+"_"+memberdb.getId();
        redisCache.deleteObject(memberKey);
      
		if(rolezd == 2) {
		 	QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
	        queryWrapper.eq("dept_dp_id", deptDpId);
	        queryWrapper.eq("rolezd",rolezd);
	        int dzsl =  memberMapper.selectCount(queryWrapper);
	        if(dzsl>0) {
	        	throw new RuntimeException("只能设置一个店长");
	        }
		}
		
		if(memberdb.getRolezd().intValue() != 0) {//不是普通会员 
			if(rolezd == 0 || rolezd == -1 || rolezd == 1) {
				QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
		        queryWrapper.eq("spreaduid",memberdb.getSpreaduid());
		        int hysl =  memberMapper.selectCount(queryWrapper);
		        if(hysl > 1) {
			        throw new RuntimeException("已经绑定有"+(hysl-1)+"个群会员，不能降级此会员");
				}
		 	}
		}
		
		if(rolezd == -1) {
			memberdb.setDeptDpId(null);
    		memberdb.setDeptTzId(null);
    		memberdb.setDeptZbjId(null);
    		memberdb.setUpdateTime(localDateTime);
    		if(memberdb.getSpreadTime()==null) {
    			memberdb.setSpreadTime(localDateTime);
    		}
    		memberdb.setUpdateBy(SecurityUtils.getUserId());
    		memberdb.setRolezd(rolezd);
    		int ret = memberMapper.updateById(memberdb);
    		if(ret>0) {

    		}
    		return ret;
		}
		
		
	 	
		if(memberdb.getDeptDpId() !=null && deptDpId.longValue() != memberdb.getDeptDpId().longValue() ) {
			int whxdds =  orderMapper.selectOrderCountByMemberId(memberId);
			if(whxdds > 0) {
		           throw new RuntimeException("此会员还有["+whxdds+"]个订单未核销！");
			}
			
			int wzfdd = this.selectOrderCountWzf(memberId);//未支付的订单
			if(wzfdd > 0) {
				throw new RuntimeException("此会员还有["+whxdds+"]个订单未支付");
			}
		}
		
		
		SysDept sysDept = deptService.selectDeptById(deptDpId);
		if(sysDept == null || sysDept.getBmlx()==null || !"5".equals(sysDept.getBmlx())) {
	           throw new RuntimeException("你选择的店铺不存在");
		}
		String ancestors = sysDept.getAncestors();
		if(ancestors!=null && ancestors.split(",").length == 4) {
	  		String[] as = sysDept.getAncestors().split(",");
    		Long deptZbjId = Long.parseLong(as[2]);
    		Long deptTzId = Long.parseLong(as[3]);
    		if(rolezd == 2 || rolezd == 3  || rolezd == 4) {//解除绑定
    			memberdb.setSpreaduid(memberId);
    		}
    		memberdb.setDeptDpId(deptDpId);
    		memberdb.setDeptTzId(deptTzId);
    		memberdb.setDeptZbjId(deptZbjId);
    		memberdb.setUpdateTime(localDateTime);
    		memberdb.setUpdateBy(SecurityUtils.getUserId());
    		memberdb.setRolezd(rolezd);
    		if(memberdb.getSpreadTime()==null) {
    			memberdb.setSpreadTime(localDateTime);
    		}
    		int ret = memberMapper.updateById(memberdb);
    		if(ret>0) {
    		 
    		}
    		return ret;
		}
        throw new RuntimeException("你选择一个有效的店铺");
		
		
	}
	
	
	/**
     * 设置为角色
     * @param member
     * @return
     */
	public int updateByDzH5(Long memberId,int rolezd) {
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
		LocalDateTime localDateTime = LocalDateTime.now();
		if(memberId == null) {
	           throw new RuntimeException("会员不存在");
		}
		Member memberdb = selectById(memberId);
		if(memberdb == null) {
	           throw new RuntimeException("会员不存在");
		}
		
		if(rolezd == -1) {//解除绑定
			memberdb.setDeptDpId(null);
    		memberdb.setDeptTzId(null);
    		memberdb.setDeptZbjId(null);
		}
		if(rolezd == 2 || rolezd == 3  || rolezd == 4) {//解除绑定
			memberdb.setSpreaduid(memberId);
		}
		
		//if(rolezd == 0 || rolezd==1 || rolezd == -1 || rolezd == 3) {
			memberdb.setUpdateTime(localDateTime);
			memberdb.setUpdateBy(member.getId());
			memberdb.setRolezd(rolezd);
			if(memberdb.getSpreadTime()==null) {
    			memberdb.setSpreadTime(localDateTime);
    		}
			int ret = memberMapper.updateById(memberdb);
			if(ret>0) {
			    String memberKey = Constants.MEMBER_INFO+"_"+memberdb.getId();
			    redisCache.deleteObject(memberKey);
			}
			return ret;
		//}else {
	    //       throw new RuntimeException("角色类型不正确");
		//}
	  
	 
		
	 
		
		
	}

	public List<MemberTopVO> listByTop(MemberTopQuery query, Pageable page) {
	    if (page != null) {
	       PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
	    }
	    return memberMapper.selectManagerOrderTopPage(query);
	}

	/**
	 * 	设置店长的其他店铺部门id
	 * @param id
	 * @param qtDeptDpIds
	 * @return
	 */
	public int updateByDzqtDpid(Long id, String qtDeptDpIds) {
		   String memberKey = Constants.MEMBER_INFO+"_"+id;
		   redisCache.deleteObject(memberKey);
		   UpdateWrapper<Member> updateWrapper = new UpdateWrapper<>();
	       updateWrapper.set("qt_dept_dp_ids",qtDeptDpIds)
	                .set("update_time",LocalDateTime.now())
	                .eq("id",id);
	       return memberMapper.update(null,updateWrapper);
	}
	
}
